package fr.ordre66.vlcs.client;

import java.lang.reflect.InvocationTargetException;

import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.headless.HeadlessMediaPlayer;

public class Player {

	private final MediaPlayerFactory factory;
	private final MediaPlayer  mediaPlayer;
	private HeadlessMediaPlayer songPlayer;
	private final String media;

	public Player(String media, String[] args)
			throws InterruptedException, InvocationTargetException {

		this.media = media;
		IHM ihm = new IHM(this);

		factory = new MediaPlayerFactory(args);
		mediaPlayer = factory.newMediaPlayer(IHM.WIDTH, IHM.HEIGHT,
				new RenderCallback(ihm.getImage(), ihm.getImagePane(), IHM.WIDTH, IHM.HEIGHT));
		songPlayer = factory.newMediaPlayer();
		mediaPlayer.playMedia(media);

		// Just to show regular media player functions still work...
		Thread.sleep(100000);

		mediaPlayer.nextChapter();
	}
	
	public void startStreaming(){
		
		String options = ":sout=#transcode{vcodec=FLV1,acodec=mp3}:duplicate{dst=display,dst=std{access=http,mux=ffmpeg{mux=flv},dst=:9090/flux.flv}}";
	    mediaPlayer.stop();
	    mediaPlayer.addMediaOptions(options);
	    mediaPlayer.play();
	}
	
	public void stopStreaming(){
		
		mediaPlayer.stop();
		mediaPlayer.playMedia(media);
	}

	public void startRecording(){
		
//		String options = ":sout=#transcode{vcodec=mp2v,vb=256,fps=25,scale=1, acodec=mpga}:duplicate{dst=display,dst=standard{access=file, mux=ps, dst=/tmp/flux.mpg}}";
		String options = ":sout=#transcode{vcodec=FLV1,acodec=mp3}:duplicate{dst=display,dst=std{access=file, mux=ffmpeg{mux=flv}, dst=/tmp/flux.flv}}";
	    mediaPlayer.stop();
	    mediaPlayer.addMediaOptions(options);
	    mediaPlayer.play();
	    try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    stopRecording();
	}
	
	public void stopRecording(){
		
		mediaPlayer.stop();
		mediaPlayer.playMedia(media);
	}
	
	public void playSong(){
		songPlayer.playMedia("/tmp/song.mp3");
	}
	
	public void stopSong(){
		songPlayer.stop();
	}
}
